/*  
 * Copyright (c) 2015-2026 LeeSon Ltd. All Rights Reserved.  
 * LeeSon  QQ:25901875
 */
package com.leeson.portal.manage.view.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.leeson.portal.manage.base.BaseAction;
import com.leeson.portal.manage.domain.Account;
import com.leeson.portal.manage.domain.PageBean;
import com.leeson.portal.manage.utils.ExcelUtils;

@Controller
@Scope("prototype")
public class AccountAction extends BaseAction<Account> {

	private static final long serialVersionUID = -4296032514753579198L;
	
    private int pageNum=1;  //当前页
    private int pageSize=10;  //每页多少条记录
	private String[] choose;
	
	private Long payTime;
	private int payType;
	
	public Long getPayTime() {
		return payTime;
	}

	public void setPayTime(Long payTime) {
		this.payTime = payTime;
	}

	public int getPayType() {
		return payType;
	}

	public void setPayType(int payType) {
		this.payType = payType;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String[] getChoose() {
		return choose;
	}

	public void setChoose(String[] choose) {
		this.choose = choose;
	}

	
	
	
	
	/**
	 * 文件上传准备
	 */
	
	//上传文件集合   
    private List<File> file;   
    //上传文件名集合   
    private List<String> fileFileName;   
    //上传文件内容类型集合   
    private List<String> fileContentType;   
    public List<File> getFile() {   
        return file;   
    }   

    public void setFile(List<File> file) {   
        this.file = file;   
    }   

   public List<String> getFileFileName() {   
       return fileFileName;   
   }   

    public void setFileFileName(List<String> fileFileName) {   
        this.fileFileName = fileFileName;   
    }   

    public List<String> getFileContentType() {   
        return fileContentType;   
    }   

    public void setFileContentType(List<String> fileContentType) {   
        this.fileContentType = fileContentType;   
    } 
    
    
    
	/**
	 * 列表（带分页）
	 * 
	 * @return
	 */
	public String list() {
		Account searchModel = new Account();
		StringBuffer sb = new StringBuffer("where 1=1 ");
		if(model.getName()!=null&&!model.getName().equals("")){
			sb.append(" and name like '%"+model.getName()+"%' ");
			searchModel.setName(model.getName());
		}
		if(model.getId()!=null&&!model.getId().equals("")){
			sb.append(" and id='"+model.getId()+"'");
			searchModel.setId(model.getId());
		}
		if(model.getLoginName()!=null&&!model.getLoginName().equals("")){
			sb.append(" and loginName like '%"+model.getLoginName()+"%' ");
			searchModel.setLoginName(model.getLoginName());
		}
		if(model.getState()!=null&&!model.getState().equals("")){
			sb.append(" and state='"+model.getState()+"'");
			searchModel.setState(model.getState());
		}
		
//		List<Account> userList = accountService.findByCondition(sb.toString());
//		ActionContext.getContext().put("userList", userList);
		
		PageBean pageBean=accountService.findByConditionWithPage(pageNum,pageSize,sb.toString());
		ActionContext.getContext().getValueStack().push(pageBean);
		ActionContext.getContext().getValueStack().push(searchModel);
		return "list";
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	public String delete() {
		accountService.delete(model.getId());
		return "toList";
	}

	/**
	 * 删除多选
	 * 
	 * @return
	 */
	public String deleteChoose() {
		if (choose != null && choose.length > 0) {
			for (int i = 0; i < choose.length; i++) {
				accountService.delete(Long.parseLong(choose[i]));
			}
		}
			
		return "toList";
	}
	
	
	/**
	 * 添加页面
	 * 
	 * @return
	 */
	public String addUI() {
		
		return "saveUI";
	}

	/**
	 * 添加
	 * 
	 * @return
	 */
	public String add() {
		if(!accountService.checkLoginName(model.getLoginName())){
			model.setLoginName("用户名已经存在");
			ActionContext.getContext().getValueStack().push(model);
			ActionContext.getContext().put("msg", "用户名已经存在");
			return "saveUI";
		}
		// >> 设置默认密码为1234（要使用MD5摘要）
		String md5Digest = DigestUtils.md5Hex("1234");
		if(!(model.getPassword().equals("")||model.getPassword()==null)){
			md5Digest=DigestUtils.md5Hex(model.getPassword());
		}
		model.setPassword(md5Digest);
		model.setDate(new Date());
		model.setTime(Long.parseLong("0"));

		// 保存到数据库
		accountService.save(model);
		return "toList";
	}

	/**
	 * 修改页面
	 * 
	 * @return
	 */
	public String editUI() {
		
		// 准备回显的数据
		Account user = accountService.getById(model.getId());
		ActionContext.getContext().getValueStack().push(user);
		return "saveUI";
	}

	/**
	 * 修改
	 * 
	 * @return
	 */
	public String edit() {
		// 1，从数据库中取出原对象
		Account user = accountService.getById(model.getId());
		String ps=model.getPassword();
		
		if(!(user.getPassword().equals(ps))&&!(ps.equals("")||ps==null)){
			String md5Digest = DigestUtils.md5Hex(model.getPassword());
			user.setPassword(md5Digest);
		}

		// 2，设置要修改的属性
		user.setLoginName(model.getLoginName());
		user.setName(model.getName());
		user.setGender(model.getGender());
		user.setPhoneNumber(model.getPhoneNumber());
		user.setEmail(model.getEmail());
		user.setDescription(model.getDescription());
		user.setState(model.getState());
		
		// 3，更新到数据库
		accountService.update(user);

		return "toList";
	}

	/**
	 * 初始化密码
	 * 
	 * @return
	 */
	public String initPassword() {
		accountService.initPassword(model.getId());
		return "toList";
	}

	/**
	 * 改变用户状态
	 * 
	 * @return
	 */
	public String editState(){
		Account user = accountService.getById(model.getId());
		int state=Integer.parseInt(user.getState());
		if(state==3){
			user.setState("0");
		}else {
			state++;
			user.setState(String.valueOf(state));
		}
		accountService.update(user);
		return "toList";
	}
	
	public String payUI(){
		// 准备回显的数据
				Account user = accountService.getById(model.getId());
				ActionContext.getContext().getValueStack().push(user);
		return "payUI";
	}
	
	public String pay(){
		Account user = accountService.getById(model.getId());
		int state=Integer.parseInt(user.getState());
		Long oldDate=user.getDate().getTime();
		Long oldTime=user.getTime();
		Long now=new Date().getTime();
		Long newDate;
		
		if(state==0){
			user.setState(String.valueOf(payType));
		}
		//买断
		if(payType==3){
			//如果记录日期小于现在
			if(oldDate<new Date().getTime()){
				newDate=now+payTime*1000*60*60;
			}else{
				newDate=oldDate+payTime*1000*60*60;
			}
			user.setDate(new Date(newDate));
			user.setState(String.valueOf(payType));
		}
		//计时
		if(payType==2){
			user.setTime(oldTime+payTime*1000*60*60);
		}
		if(state==1){
			user.setState(String.valueOf(state));
		}
		accountService.update(user);
		return "toList";
	}
	
	public String out(){
		List<Account> accounts=accountService.list();
		String cfgPath = ServletActionContext.getServletContext().getRealPath("/");
		Date now=new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); 
		String nowString=format.format(now);
		File dir=new File(cfgPath + "ExcelOut/");
		if(!dir.exists()){
			dir.mkdirs();
		}
		String fileName = cfgPath + "ExcelOut/" +nowString+".xls";
		try {
			ExcelUtils.writeAccountToExcel(fileName, accounts);
		} catch (Exception e) {
			e.printStackTrace();
			ActionContext.getContext().put("msg", "文件创建失败！");
			ActionContext.getContext().put("downUrl", 0);
			return "out";
		}
		ActionContext.getContext().put("msg", "文件创建成功！");
		ActionContext.getContext().put("downUrl", nowString+".xls");
		ActionContext.getContext().put("creatDate", nowString);
		return "out";
	}
	
	public String in(){
		ActionContext.getContext().put("msg", "接入账户文件导入!");
		return "in";
	}
	
	public String doIn(){
		String dir;
		String nowString;
		List<Account> unInAccounts=new ArrayList<Account>();
		try {   
            InputStream in = new FileInputStream(file.get(0));   
            dir = ServletActionContext.getServletContext().getRealPath("/ExcelIn");  
            File fileLocation = new File(dir);  
            //此处也可以在应用根目录手动建立目标上传目录  
            if(!fileLocation.exists()){  
                boolean isCreated  = fileLocation.mkdir();  
                if(!isCreated) {  
                    //目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。  
                	ActionContext.getContext().put("msg", "权限不足!");
                	ActionContext.getContext().put("err", 0);
        			return "in";
                }  
            }  
            String fileName=this.getFileFileName().get(0);  
            int pos = fileName.lastIndexOf( "." );   
            String kzm=fileName.substring(pos);   
            if(!(kzm.equals(".xls")||kzm.equals(".xlsx"))){
            	ActionContext.getContext().put("msg", "文件格式错误!");
            	ActionContext.getContext().put("err", 0);
    			return "in";
            }
            
            Date now=new Date();
    		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); 
    		nowString=format.format(now);
            
            File uploadFile = new File(dir, nowString+".xls");   
            OutputStream out = new FileOutputStream(uploadFile);   
            byte[] buffer = new byte[1024 * 1024];   
            int length;   
            while ((length = in.read(buffer)) > 0) {   
                out.write(buffer, 0, length);   
            }   
            in.close();   
            out.close();   
        } catch (Exception ex) {   
        	ActionContext.getContext().put("msg", "文件格式错误!");
        	ActionContext.getContext().put("err", 0);
			return "in";
        }
		
		try {
			List<Account> accounts=ExcelUtils.readExcelAccount(dir+"/"+nowString+".xls");
			for (int i = 0; i < accounts.size(); i++) {
				if(!accountService.checkLoginName(accounts.get(i).getLoginName())){
					unInAccounts.add(accounts.get(i));
				}else {
					accountService.save(accounts.get(i));
				}
				
			}
		} catch (Exception e) {
			ActionContext.getContext().put("msg", "文件格式错误!");
			ActionContext.getContext().put("err", 0);
			return "in";
		}
      
		ActionContext.getContext().put("unInAccounts", unInAccounts);
		
		return "doInResult";
	}
	
}
